<template>
  <div class="update-photo">
    <img class="image" :src="image">
    <van-nav-bar
      class="toolbar"
      left-text="取消"
      right-text="确认"
      @click-left="$emit('close')"
      @click-right="onConfirm"
    ></van-nav-bar>
  </div>
</template>

<script>
import { updateUserPhoto } from '@/api/user.js'
import 'cropperjs/dist/cropper.css'
import Cropper from 'cropperjs'
export default {
  name: 'UpdatePhoto',
  props: {
    file: {
      required: true
    }
  },
  components: {},
  data () {
    return {
      image: window.URL.createObjectURL(this.file),
      cropper: null
    }
  },
  computed: {},
  watch: {},
  methods: {
    getCroppedCanvas () {
      return new Promise((resolve, reject) => {
        this.cropper.getCroppedCanvas().toBlob((bolb) => {
          resolve(bolb)
        })
      })
    },
    async onConfirm () {
      const bolb = await this.getCroppedCanvas()
      const fd = new FormData()
      fd.append('photo', bolb)
      await updateUserPhoto(fd)
      this.$emit('update-photo', window.URL.createObjectURL(Blob))
      this.$emit('close')
      this.$toast.success('修改头像成功成功')
    }
  },
  created () {
  },
  mounted () {
    const image = this.$refs.image
    this.cropper = new Cropper(image, {
      viewMode: 1,
      dragMode: 'move',
      aspectRatio: 1,
      cropBoxMovable: false,
      cropBoxResizable: false,
      background: false,
      movable: true
    })
  },
  destroyed () {
  }
}
</script>

<style scoped lang='less'>
.update-photo {
  .image {
    display: block;
    max-width: 100%;
  }
  .toolbar {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: #000000;
  }
}
</style>
